﻿using System;
using System.Data;
using System.Configuration;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;
using System.Text.RegularExpressions;
using System.IO;

namespace TA.Turbo
{
	/// <summary>
	/// Handles requests for included resources.
	/// </summary>
	public class ResourceHandler : IHttpHandler
	{
		#region PUBLIC
		#region INIT
		/// <summary>
		/// Ctor.
		/// </summary>
		public ResourceHandler()
		{
		}
		#endregion
		#endregion
		#region INTERNAL
		#region VARS
		#endregion
		#region METHODS
		#region IHttpHandler Members
		/// <summary>
		/// Gets true.
		/// </summary>
		public bool IsReusable
		{
			get { return true; }
		}
		/// <summary>
		/// Processes a valid request by outputting the corresponding resource content.
		/// </summary>
		/// <param name="context"></param>
		public void ProcessRequest(HttpContext context)
		{
			if (!string.IsNullOrEmpty(context.Request["k"]))
			{
				string keyString = context.Request["k"];

				long key;
				if (!long.TryParse(keyString, out key))
					throw new InvalidOperationException("The specified key is not valid.");

				CombinedContent cc;
				if (!CombinedContent.CachedContent.TryGetValue(key, out cc))
				{
					throw new InvalidOperationException("The specified key wasn't found.");
				}

				if (!string.IsNullOrEmpty(cc.ContentType))
					context.Response.ContentType = cc.ContentType;
				// TODO: add caching headers
				//	context.Response.AddHeader(
				context.Response.Write(cc.Text);
			}
			else if (!string.IsNullOrEmpty(context.Request["f"]))
			{
				string filePath = context.Request["f"];
				if (!filePath.StartsWith("/") || !filePath.StartsWith("~/"))
					throw new InvalidOperationException("File path has to be relative to the web application's root.");

				filePath = context.Server.MapPath(filePath);
				switch (Path.GetExtension(filePath).ToLower())
				{
					case "js":
						context.Response.ContentType = "text/javascript"; break;
					case "css":
						context.Response.ContentType = "text/css"; break;
				}
				context.Response.WriteFile(filePath);
			}
			else
				throw new InvalidOperationException("Invalid request.");

			context.Response.End();
		}

		#endregion
		#endregion
		#endregion

	}
}